﻿using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.Microsoft.AspNetCore.Razor.TagHelpers;
using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers;

namespace Bangle.Abp.TagHelperPlus.TagHelpers.DateRange
{
    public class AbpDateRangeTagHelperService : AbpTagHelperService<AbpDateRangeTagHelper>
    {
        public AbpDateRangeTagHelperService()
        {
        }

        public async override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            var startName = string.IsNullOrEmpty(TagHelper.StartName) ? TagHelper.AspStartFor.Name : TagHelper.StartName;
            var endName = string.IsNullOrEmpty(TagHelper.EndName) ? TagHelper.AspEndFor.Name : TagHelper.EndName;

            var startVal = TagHelper.AspStartFor.Model == null ? "" : Convert.ToDateTime(TagHelper.AspStartFor.Model).ToString("yyyy-MM-dd");
            var endVal = TagHelper.AspEndFor.Model == null ? "" : Convert.ToDateTime(TagHelper.AspEndFor.Model).ToString("yyyy-MM-dd");
            var labelHtml = await GetLabelAsHtmlAsync(context, output);
            var sbHtml = new StringBuilder();
            sbHtml.AppendLine(labelHtml);
            sbHtml.AppendLine("<div class=\"input-daterange input-group form-control\">");
            sbHtml.AppendLine($"<input type=\"text\" name=\"{startName}\" value=\"{startVal}\" style=\"width:6rem;border:none\" />");
            sbHtml.AppendLine("<span class=\"input-group-addon\">-</span>");
            sbHtml.AppendLine($"<input type=\"text\" name=\"{endName}\" value=\"{endVal}\" style=\"width:6rem;border:none\" />");
            sbHtml.AppendLine("</div>");

            output.TagName = "div";
            output.Attributes.AddClass("mb-3 abp-date-range");
            output.TagMode = TagMode.StartTagAndEndTag;
            output.PreContent.AppendHtml(sbHtml.ToString());
        }

        protected virtual async Task<string> GetLabelAsHtmlAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (!string.IsNullOrEmpty(TagHelper.Label))
            {
                var label = new TagBuilder("label");
                label.InnerHtml.AppendHtml(TagHelper.Label);
                return label.ToHtmlString();
            }
            return await Task.FromResult("");
        }

    }
}